package cn.miju.ser.common.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.miju.database.constant.DbConstant;
import cn.miju.database.entity.PayOrder;
import cn.miju.database.service.PayOrderDataService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.JobDataMap;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <pre>
 * 待支付订单超时处理定时任务（消息队列未处理/未成功处理）
 * </pre>
 *
 * @author zhuming
 * @version 1.0.0
 * @since 2023-03-11 15:55
 */
@Slf4j
@Component
@DisallowConcurrentExecution
public class WaitingPayOrderQuartzJob extends QuartzJobBean {
    @Autowired
    private PayOrderDataService payOrderDataService;
    @Override
    protected void executeInternal(JobExecutionContext context) {
        JobDataMap jobDataMap = context.getMergedJobDataMap();
        // 查询下单时间在queryOrderTimeSecond秒之前的待支付订单
        int queryOrderTimeSecond = (int) jobDataMap.get("query_order_time_second");
        List<PayOrder> payOrderList = payOrderDataService.list(new LambdaQueryWrapper<PayOrder>().
                le(PayOrder::getCreatedOrderTime, LocalDateTime.now().minusSeconds(queryOrderTimeSecond)).
                eq(PayOrder::getStatus, DbConstant.PayOrderStatus.WAITING));
        if (CollectionUtil.isNotEmpty(payOrderList)) {
            // 支付宝支付订单
            List<PayOrder> alipayOrderList = payOrderList.stream().
                    filter(payOrder -> DbConstant.PayWay.ALIPAY.equals(payOrder.getPayWay())).collect(Collectors.toList());
            if (CollectionUtil.isNotEmpty(alipayOrderList)) {
                //扫码支付订单因为支付宝不扫描二维码就没有订单，所以直接更新超时，不用去查
                List<PayOrder> scanCodeOrderList = alipayOrderList.stream().
                        filter(payOrder -> DbConstant.PayScen.SCAN_CODE.equals(payOrder.getPayScen())).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(scanCodeOrderList)) {
                    scanCodeOrderList.forEach(payOrder -> {
                        payOrder.setStatus(DbConstant.PayOrderStatus.TIMEOUT);
                        payOrder.setUpdatedTime(LocalDateTime.now());
                    });
                    payOrderDataService.updateBatchById(scanCodeOrderList);
                }
                // TODO 其他支付场景订单处理待补充
            }
            // TODO 其他支付方式订单处理待补充
        }

    }
}
